<template>
  <view class="home">
		<view class="btn_box">
			<u-button class="btn_import" type="primary" color="#1890FF" shape="circle" text="导入" @click="chooseZip"></u-button>
			<u-button class="btn_import" type="primary" color="#1890FF" shape="circle" text="导出" @click="exportZip"></u-button>
		</view>
    
    <image v-if="systems.length === 0" class="empty_img" src="../../static/images/empty.png" mode=""></image>

    <view class="system_card">
      <u-row justify="space-between" :gutter="20">
        <u-col span="3" v-for="(system, index) in systems" :key="index">
          <view class="system_box" @click="goToSystem(system)">
            <u-row>
              <u-col span="9">
                <text class="system_name">{{ system.name }}</text>
              </u-col>
              <u-col span="3">
                <u-tag class="system_secret" :text="system.secretLevel" shape="circle" :bgColor="system.secretLevel === '非密' ? '#1890FF' : (system.secretLevel === '秘密' ? '#F68330' : '#EF5757')"></u-tag>
              </u-col>
            </u-row>

            <view class="system_version_box">
              <view class="gradient-dashed-line"></view>
              <image class="version_icon" src="../../static/images/version_icon.png" mode=""></image>
              <text class="version_text">版本V{{ system.version }}</text>
            </view>
          </view>
        </u-col>
      </u-row>
    </view>
  </view>
</template>

<script>
import { ApplicationServiceImpl } from '../../uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/service/impl/ApplicationServiceImpl';
import { openSqlite } from "../../uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/db/SqliteHelper";

const applicationService = new ApplicationServiceImpl()
export default {
  data() {
    return {
      systems: [],
      zipPath: '',
			fileList: []
    }
  },
  onReady() {
    this.requestPermission()

    this.loadApp()
  },
  methods: {
    // 加载所有应用数据，数据列表
    loadApp() {
      applicationService.getBusApplications().then((res) => {
        this.systems = res
        console.log("查询所有应用成功", res)
      })
      .catch((err) => {
        console.error("查询所有应用失败", err)
      });
    },

    // 保存应用数据
    async saveApp(json, url) {
      if (await applicationService.saveApp(json.name, json.dbName, json.secretLevel, json.version, url)) {
        console.log("保存成功")
				await this.loadApp()
      } else {
        console.error("保存失败")
      }

    },
    requestPermission() {
      // 安卓系统才请求权限
      if (uni.getSystemInfoSync().platform === 'android') {
        plus.android.requestPermissions(
            [
              'android.permission.READ_EXTERNAL_STORAGE',
              'android.permission.WRITE_EXTERNAL_STORAGE'
            ],
            (result) => {
              if (result.granted.length <= 0) {
                uni.showToast({title: '请授权存储权限', icon: 'none'})
              }
            },
            (error) => {
              console.error('权限请求失败:', error)
            }
        );
      }
    },

    // 导入
    chooseZip() {
      console.log('点击了');
      const main = plus.android.runtimeMainActivity();
      const Intent = plus.android.importClass("android.content.Intent");
      const Activity = plus.android.importClass("android.app.Activity");
      const intent = new Intent(Intent.ACTION_GET_CONTENT);
      intent.addCategory(Intent.CATEGORY_OPENABLE);
      intent.setType("application/zip");

      const REQUEST_CODE = 1;

      main.onActivityResult = (requestCode, code, data) => {
        if (code == Activity.RESULT_OK && requestCode == REQUEST_CODE) {
          let fileUri = data.getData();

          console.log('--------Uri:', fileUri ? fileUri.toString() : 'Uri为空');

          const resolver = main.getContentResolver();
          plus.android.importClass(resolver);
          const cursor = resolver.query(fileUri, null, null, null, null);
          let fileName = 'myzip.zip'; // 默认名

          if (cursor) {
            plus.android.importClass(cursor);
            if (cursor.moveToFirst()) {
              const nameIndex = cursor.getColumnIndex('_display_name');
              if (nameIndex >= 0) {
                fileName = cursor.getString(nameIndex);
                console.log('获取的文件名:', fileName);
                this.copyZipFromDownloadToApp(fileName)
              }
            }
            cursor.close();
          }
        }
      };

      main.startActivityForResult(intent, REQUEST_CODE);
    },

    // 复制文件函数
    copyZipFromDownloadToApp(zipFileName) {
      const downloadPath = '/storage/emulated/0/Download/' + zipFileName;

      // 获取目标路径（app 私有目录）
      plus.io.requestFileSystem(plus.io.PRIVATE_DOC, (fs) => {
        // 读取 Download 下的 zip 文件对象
        plus.io.resolveLocalFileSystemURL(downloadPath, (entry) => {
          entry.copyTo(
              fs.root,
              zipFileName,
              (newEntry) => {
                console.log('复制成功，目标路径：' + newEntry.fullPath);
                // 可以继续对这个 zip 进行解压操作
                this.unzipFile(zipFileName)
              },
              (err) => {
                console.error('复制失败：', err);
                uni.showToast({title: '复制失败', icon: 'none'});
              }
          );
        }, (err) => {
          console.error('找不到文件：', err);
          uni.showToast({title: '文件不存在', icon: 'none'});
        });
      }, (err) => {
        console.error('获取私有目录失败：', err);
        uni.showToast({title: '获取目录失败', icon: 'none'});
      });
    },

    // 解压zip
    unzipFile(zipFileName) {
      const zipPath = '_doc/' + zipFileName;                       // zip 源路径（复制后的）
      const targetPath = '_doc/unzip/';                            // 解压后的目录
      const folderName = zipFileName.replace(/\.zip$/i, '')        // 去掉 .zip 后的文件名
      const configPath = targetPath + folderName + '/config.json'  // config.json 路径
			const systemUrl = targetPath + folderName + '/dist/index.html'

      plus.zip.decompress(zipPath, targetPath, () => {
          console.log('解压成功，config路径是', configPath);
          console.log('解压成功，index路径是', systemUrl);
          uni.showToast({title: '解压成功', icon: 'success'});

          // 如果要查看解压的内容，可以在这里列出文件

          // 解压后，读取config.json文件
          this.readConfigJson(configPath, systemUrl)
        }, (err) => {
          console.error('解压失败: ', err);
          uni.showToast({title: '解压失败', icon: 'none'});
        }
      );
    },

    // 可选：列出解压后的文件（仅调试用）
    listUnzippedFiles(dirPath) {
      plus.io.resolveLocalFileSystemURL(dirPath, function (dirEntry) {
        const directoryReader = dirEntry.createReader();
        directoryReader.readEntries(function (entries) {
          console.log('解压内容：');
          for (let i = 0; i < entries.length; i++) {
            console.log(entries[i].name);
          }
        }, function (err) {
          console.error('读取解压目录失败', err);
        });
      });
    },

    // 读取config.json
    readConfigJson(configPath, systemUrl) {
      let _this = this
      plus.io.resolveLocalFileSystemURL(configPath, function (fileEntry) {
        fileEntry.file(function (file) {
          const reader = new plus.io.FileReader();
          reader.onloadend = function (evt) {
            try {
              const jsonData = JSON.parse(evt.target.result);
              
              console.log('读取成功:', jsonData);

              _this.saveApp(jsonData, systemUrl)

              // 你可以在这里操作 jsonData，比如赋值到 data、跳转页面等
            } catch (err) {
              console.error('JSON 解析失败：', err);
            }
          };
          reader.readAsText(file); // 👈 以文本方式读取
        }, function (err) {
          console.error('获取 file 失败：', err);
        });
      }, function (err) {
        console.error('找不到 config.json 文件：', err);
      });
    },

    // 进入业务系统
    goToSystem(system) {
      // 打开数据库，防止因库未打开导致sql执行是啊比
      openSqlite(system.dbName, system.dbPath)
      const url = system.url
      console.log('打开系统页面:', url)
			
			plus.io.resolveLocalFileSystemURL(url, (entry) => {
			  const localUrl = entry.toLocalURL(); // ✅ 自动带上 file:// 协议
			
			  // 用这个路径去赋值给 WebView
			  console.log('localUrl页面路径：', localUrl);
				
				uni.navigateTo({
				  url: `/pages/system/systemDetail?htmlPath=${encodeURIComponent(localUrl)}`
				})
			})
			
      
    },
		
		// 导出
		exportZip() {
			console.log(this.systems, '11111111')
			let sourceFilePath = this.systems[0].dbPath
      let path = plus.io.convertAbsoluteFileSystem( sourceFilePath );
			let zipFileName = this.systems[0].code + '.zip'
			
			this.compressFileToDownload(path, zipFileName)
		},
		
		// 压缩
		compressFileToDownload(sourceFilePath, zipFileName) {
		  // sourceFilePath: 如 "_doc/myfolder/myfile.txt"
		  // zipFileName: 不含路径，仅文件名，如 "myfile.zip"
		
		  // 获取 Download 目录路径
		  plus.io.requestFileSystem(plus.io.PUBLIC_DOWNLOADS, (fs) => {
				console.log('fs', fs)
		    
		    const zipDestPath = fs.root.toURL() + zipFileName; // 公共下载目录下的目标 zip 文件
		
		    // 开始压缩
		    plus.zip.compress(sourceFilePath, zipDestPath,
		      () => {
		        console.log('压缩成功：' + zipDestPath);
		        uni.showToast({ title: '压缩成功', icon: 'success' });
		      },
		      (err) => {
		        console.error('压缩失败：', err);
		        uni.showToast({ title: '压缩失败', icon: 'none' });
		      }
		    );
		
		  }, (err) => {
		    console.error('无法访问 Download 目录：', err);
		    uni.showToast({ title: '访问Download目录失败', icon: 'none' });
		  });
		},
  }
}
</script>

<style lang="scss" scoped>
.home {
  height: 100%;
  background: #fff;
  border-radius: 10px;
  position: relative;
  padding: 20px;
  display: flex;
  flex-direction: column;

  .empty_img {
    position: absolute;
    bottom: 0;
    width: 100%;
  }
	
	.btn_box {
		justify-content: space-between;
		display: flex;

		.btn_import {
			width: 84px;
			height: 32px;
			margin-left: 0;
			margin-right: 0;
		}
	}

  .system_card {
    flex: 1;
    margin-top: 20px;

    .system_box {
      height: 90px;
      padding: 16px;
      border-radius: 10px;
      background: linear-gradient(171.54deg, #F6FAFF 12.94%, #FFFFFF 100%);
      border: 1px solid rgba(24, 144, 255, 0.8);
      position: relative;

      .system_name {
        font-size: 16px;
        font-weight: 500;
      }

      .system_secret {
        font-size: 14px;
				text-align: center;
      }

      .system_version_box {
        width: 100%;
        position: absolute;
        bottom: 0;
        left: 0;
        height: 32px;
        line-height: 32px;
        background: linear-gradient(90deg, rgba(24, 144, 255, 0) 0%, rgba(24, 144, 255, 0.08) 50%, rgba(24, 144, 255, 0) 100%);
        text-align: center;

        .gradient-dashed-line {
          border-top: 1px dashed transparent;
          height: 0;
          border-image: linear-gradient(90deg, rgba(24, 144, 255, 0) 0%, rgba(24, 144, 255, 0.6) 50%, rgba(24, 144, 255, 0) 100%);
          border-image-slice: 1;
        }

        .version_icon {
          width: 18px;
          height: 18px;
          margin-right: 4rpx;
        }

        .version_text {
          color: #797A80;
          font-size: 14px;
        }
      }
    }
  }
}
</style>
